package com.kdd.campus.sh.controller;

import com.kdd.campus.common.entity.CommonResult;
import com.kdd.campus.common.util.RedisUtil;
import com.kdd.campus.sh.dto.CommentDto;
import com.kdd.campus.sh.po.ShComment;
import com.kdd.campus.sh.service.CommentService;
import com.kdd.campus.sh.util.JwtTokenUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/****
 * @Author:shenkunlin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/
@Api(value = "商品评论(留言)")
@RestController
@RequestMapping("/comment")
@CrossOrigin
public class CommentController extends BaseController{

    @Autowired
    private CommentService commentService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    /***
     * 根据商品ID查询商品留言信息
     * @return
     */
    @ApiOperation(value = "根据商品ID查询商品留言信息")
    @ApiImplicitParam(paramType = "path", name = "productId", value = "商品id", required = true, dataType = "Long")
    @GetMapping("/{productId}")
    public CommonResult<List<CommentDto>> findById(@PathVariable(required = true) Long productId){
        Long userId = null;
        try {
            userId = Integer.toUnsignedLong((Integer) RedisUtil.get(jwtTokenUtil.getToken(request)));
        } catch (Exception e) {
        }
        List<CommentDto> comments = commentService.findByProductId(productId,userId);
        return CommonResult.success(comments);
    }

    /***
     * 增加商品留言
     * @return
     */
    @ApiOperation(value = "增加商品留言")
    @PostMapping
    public CommonResult add(@RequestBody  @ApiParam(name = "ShComment对象",value = "传入comment JSON对象",required = true) @Validated ShComment comment){
        // 根据token，获取Redis中的userId
        Long userId = Integer.toUnsignedLong((Integer) RedisUtil.get(jwtTokenUtil.getToken(request)));
        comment.setUserId(userId);

        //调用ShCommentService实现添加ShComment
        commentService.add(comment);
        return CommonResult.success();
    }


    /***
     * 根据ID删除留言信息
     * @param commentId
     * @return
     */
    @ApiOperation(value = "根据ID删除留言信息")
    @ApiImplicitParam(paramType = "path", name = "commentId", value = "commentId", required = true, dataType = "Long")
    @DeleteMapping(value = "/{commentId}" )
    public CommonResult delete(@PathVariable Long commentId){
        // 根据token，获取Redis中的userId
        Long userId = Integer.toUnsignedLong((Integer) RedisUtil.get(jwtTokenUtil.getToken(request)));

        //调用ShCommentService实现根据主键删除
        commentService.delete(userId, commentId);
        return CommonResult.success();
    }




}
